<template>
  <div class="image-preview">
    <el-image
      v-if="imageUrl"
      :src="imageUrl"
      fit="contain"
      :preview-src-list="[imageUrl]"
      :initial-index="0"
      class="preview-image"
    >
      <template #error>
        <div class="image-error">
          <el-icon :size="100">
            <Picture />
          </el-icon>
          <p>图片加载失败</p>
        </div>
      </template>
    </el-image>

    <div v-else class="loading-container">
      <el-icon class="is-loading" :size="50">
        <Loading />
      </el-icon>
      <p>图片加载中...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { Picture, Loading } from '@element-plus/icons-vue'
import { readFileContent } from '../../utils/fileHelper'

const props = defineProps({
  file: {
    type: Object,
    required: true
  }
})

const imageUrl = ref('')

// 加载图片
const loadImage = async () => {
  try {
    imageUrl.value = ''
    
    // 如果是 URL 文件，直接使用 URL
    if (props.file.isUrl) {
      imageUrl.value = props.file.url
      console.log('✓ 使用 URL 加载图片:', props.file.url)
    } else {
      // 本地文件，读取内容
      const url = await readFileContent(props.file.raw, 'dataURL')
      imageUrl.value = url
      console.log('✓ 使用本地文件加载图片')
    }
  } catch (error) {
    console.error('图片加载失败:', error)
  }
}

watch(() => props.file, () => {
  if (props.file) {
    loadImage()
  }
}, { immediate: true })

onMounted(() => {
  if (props.file) {
    loadImage()
  }
})
</script>

<style scoped>
.image-preview {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

:deep(.el-image__inner) {
  max-width: 90%;
  max-height: 90vh;
  width: auto;
  height: auto;
  object-fit: contain;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  padding: 50px;
}

.image-error p {
  margin-top: 16px;
  font-size: 14px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #409EFF;
}

.loading-container p {
  margin-top: 16px;
  font-size: 14px;
}
</style>

